<?php

class AdminCourseSelection_Controller extends Admin_Controller {
	public function index(Request $request, Response $response) {
		$size = intval($request->size) ?: 30;
		$p = intval($request->p ?: 1);
		$from = ($p - 1) * $size;
		$q = new TrueQuery();
		if ($request->search) {
			$subQuery = new SearchQuery('name', $request->search);
			$courses = Course::find($subQuery, ['nolimit' => 1]);
			if (!$courses) {
				$students = Student::find($subQuery, ['nolimit' => 1]);
				if (!$students) {
					$q = new Query('id', -1);
				} else {
					$q = new InQuery('studentId', object_map($students, 'id'));
				}
			} else {
				$courseClasses = CourseClass::find(new InQuery('courseId', object_map($courses, 'id')), ['nolimit' => 1]);
				if (!$courseClasses) {
					$q = new Query('id', -1);
				} else {
					$q = new InQuery('courseClassId', object_map($courseClasses, 'id'));
				}
			}
		}
		$data = CourseSelection::find($q, ['from' => $from, 'size' => $size, 'sort' => ['created' => 'ASC']]);
		$page_nav['count'] = CourseSelection::totalCount($q);
		$nav = new SubPages($size, $page_nav['count'], $p, 10, "/admin/courseSelection/?p=",2);
		$page_nav['nav'] = $nav->subPageCss2();
		$classTimes = [];
		/**
		 * @var CourseSelection $courseSelection
		 */
		foreach ($data as $courseSelection) $classTimes[$courseSelection->id] = $courseSelection->courseClass()->classTime();
		$response->append(new View('admin/courseSelection/list', compact('data', 'page_nav', 'classTimes')));
	}
	public function delete(Request $request, Response $response) {
		if (!$request->path(3)) $response->alertErrorAndGoBack('请求无效！');
		/**
		 * @var CourseSelection $courseSelection
		 */
		if (!($courseSelection = CourseSelection::load($request->path(3)))) $response->alertAndGoTo('该记录不存在！', '/admin/courseSelection/');
		$courseSelection->remove();
		$response->alertAndGoTo('删除成功!', '/admin/courseSelection/');
	}
}